package com.hcinfos.gsoo.ui;

import org.json.JSONObject;

import com.hcinfos.gsoo.GsooApplication;
import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.config.Common;
import com.hcinfos.gsoo.config.Urls;
import com.hcinfos.gsoo.https.HttpClientUtil;
import com.hcinfos.gsoo.util.DialogUtil;
import com.hcinfos.gsoo.util.LogUtil;
import com.hcinfos.gsoo.util.LoginUtil;
import com.hcinfos.gsoo.util.SharePreferenceUtil;
import com.hcinfos.gsoo.util.UtilHttp;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class UpdatePwdActivity extends Activity implements OnClickListener {

	private EditText old_et;
	private EditText new_et;
	private EditText rep_et;
	private Button update_bt;
	private ImageView back_iv;
	private Dialog dialog;
	private SharePreferenceUtil spfUtil;
	private Context context;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		int width = this.getWindowManager().getDefaultDisplay().getWidth();
		Common.PROPORTION = width / 320f;
		Common.WIDTH = width;
		context = this;
		setContentView(R.layout.activity_update_pwd);
		spfUtil = new SharePreferenceUtil(this, "setting");
		dialog = createWaitDialog(this, "密码修改中");
		old_et = (EditText) findViewById(R.id.old_et);
		new_et = (EditText) findViewById(R.id.new_et);
		rep_et = (EditText) findViewById(R.id.rep_et);
		update_bt = (Button) findViewById(R.id.update_bt);
		update_bt.setOnClickListener(this);
		back_iv = (ImageView) findViewById(R.id.back_iv);
		back_iv.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.update_bt:
			updatePwd();
			break;
		case R.id.back_iv:
			finish();
			break;
		}
	}

	public TextView msg_tv;

	public Dialog createWaitDialog(final Activity activity, String msg) {
		LayoutInflater inflater = activity.getLayoutInflater();
		RelativeLayout dialog_rl = (RelativeLayout) inflater.inflate(
				R.layout.progress_wait_view, null);

		msg_tv = (TextView) dialog_rl.findViewById(R.id.RequestLoadingText);
		if (msg == null) {
			msg_tv.setText("服务连接中..");
		} else {
			msg_tv.setText(msg);
		}
		final Dialog dialog = new Dialog(activity, R.style.QuitDialog);
		dialog.setContentView(dialog_rl);
		Window dialogWindow = dialog.getWindow();
		WindowManager.LayoutParams lp = dialogWindow.getAttributes();
		dialogWindow.setGravity(Gravity.CENTER);
		lp.width = (int) (280 * Common.PROPORTION); // 宽度
		lp.height = (int) (180 * Common.PROPORTION); // 高度
		dialogWindow.setAttributes(lp);
		return dialog;
	}

	public final int UPDATE_SUCCESS = 0x2210;
	public final int UPDATE_FAIL = UPDATE_SUCCESS + 1;
	public final int LOGOUT_FAIL = UPDATE_SUCCESS + 2;
	public final int LOGOUT_SUCCESS = UPDATE_SUCCESS + 3;
	public final int NEED = UPDATE_SUCCESS + 4;

	private void updatePwd() {

		String old = old_et.getText().toString();
		String newPwd = new_et.getText().toString();
		String rep = rep_et.getText().toString();
		if (TextUtils.isEmpty(old) || TextUtils.isEmpty(newPwd)
				|| TextUtils.isEmpty(rep)) {
			Toast.makeText(this, "密码不能为空", 500).show();
			return;
		}
		if (!newPwd.equals(rep)) {
			Toast.makeText(this, "2次输入的密码不一致", 500).show();
			return;
		}
		dialog.show();

		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		params.addBodyParameter("userModify.oldPwd", old);
		params.addBodyParameter("userModify.newPwd", newPwd);
		params.addBodyParameter("userModify.checkPwd", rep);
		http.send(HttpRequest.HttpMethod.POST, Urls.updatePwd, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						try {
							String result = responseInfo.result;
							try {
								LogUtil.d("wxf", "result=" + result);
								JSONObject obj = new JSONObject(result);
								String message = obj.getString("message");
								int state = obj.getInt("state");
								if (state == 200) {
									handler.sendEmptyMessage(UPDATE_SUCCESS);
								} else if (state == 198) {
									handler.sendEmptyMessage(NEED);
								} else {
									Message msg = handler.obtainMessage();
									msg.obj = message;
									msg.what = UPDATE_FAIL;
									handler.sendMessage(msg);
								}
							} catch (Exception e) {
								handler.sendEmptyMessage(UPDATE_FAIL);
							}

						} catch (Exception e) {
							handler.sendEmptyMessage(UPDATE_FAIL);
						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {

						handler.sendEmptyMessage(UPDATE_FAIL);
					}

				});
	}

	/**
	 * 注销
	 */
	private void logOut() {

		dialog.show();
		new Thread(new Runnable() {

			@Override
			public void run() {

				try {
					String result = HttpClientUtil.getFromWebByHttpClient(
							UpdatePwdActivity.this, Urls.USER_LOGOUT);
					if (result == null) {
						Message msg = handler.obtainMessage();
						msg.what = LOGOUT_FAIL;
						handler.sendMessage(msg);
					} else {

						JSONObject obj = new JSONObject(result);
						int state = obj.getInt("state");
						String message = obj.getString("message");
						if (state == 200) {
							Message msg = handler.obtainMessage();
							msg.what = LOGOUT_SUCCESS;
							handler.sendMessage(msg);
						} else {
							Message msg = handler.obtainMessage();
							msg.what = LOGOUT_FAIL;
							msg.obj = message;
							handler.sendMessage(msg);
						}
					}
					LogUtil.d("wxf", "result:" + result);
				} catch (Exception e) {
					Message msg = handler.obtainMessage();
					msg.what = LOGOUT_FAIL;
					handler.sendMessage(msg);
					LogUtil.d("wxf", "e:" + e.toString());
				}
			}
		}).start();
	}

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case UPDATE_SUCCESS:
				msg_tv.setText("注销中...");
				logOut();
				break;
			case UPDATE_FAIL:
				dialog.dismiss();
				String error = "修改失败!";
				if (msg.obj != null) {
					error = msg.obj.toString();
				}
				Toast.makeText(UpdatePwdActivity.this, error, 500).show();

				break;
			case LOGOUT_FAIL:
				dialog.dismiss();
				Toast.makeText(UpdatePwdActivity.this, "注销失败!", 500).show();
				break;
			case LOGOUT_SUCCESS:
				dialog.dismiss();
				GsooApplication.getInstance().logout();
				spfUtil.removeKey("user");
				spfUtil.removeKey("userName");
				spfUtil.removeKey("password");
				spfUtil.removeKey("email");
				Toast.makeText(UpdatePwdActivity.this, "修改成功!", 500).show();
				Intent intent = new Intent(UpdatePwdActivity.this,
						LoginActivity.class);
				startActivity(intent);
				finish();
				break;
			case NEED:
				LoginUtil.isLoginSuccess(context, handler);
				break;
			case LoginUtil.LOGIN_FAIL:
				dialog.dismiss();
				Toast.makeText(UpdatePwdActivity.this, "修改失败!", 500).show();
				break;
			case LoginUtil.LOGIN_SUCCESS:
				updatePwd();
				break;
			}
		};
	};
}
